//
//  PHNetworktools.swift
//  PHWeibo
//
//  Created by 潘荟 on 16/7/22.
//  Copyright © 2016年 BAT. All rights reserved.
//

import UIKit
import AFNetworking

enum PHNetworktoolsType: String {
    case GET = "GET"
    case POST = "POST"
}


class PHNetworktools: AFHTTPSessionManager {
    
    //全局访问点
    static let sharedTools:PHNetworktools = {
       let tools = PHNetworktools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    
    func request(type: PHNetworktoolsType,urlString: String,parameters:AnyObject?,success:(response: AnyObject?)->(),failure:(error: NSError)->()){
        if type == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
            })
        }else {
            POST(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
            })
        }
    }

}

// MARK: - 请求OAuth数据
extension PHNetworktools{
    //请求userAccount
    func oauthLoadUserAccount(code:String,success:(response: AnyObject?)->(),failure:(error: NSError)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = [
            "client_id" : APPKEY,
            "client_secret" : APPSECRET,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : APPREDIRECT_URI
        
        ]
        
        request(PHNetworktoolsType.POST, urlString: urlString, parameters: params, success: success, failure: failure)
        
    }
    //请求用户信息数据
    func oauthLoadUserInfo(userAccount:PHUserAccount,success:(response: AnyObject?)->(),failure:(error: NSError)->()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = [
            
        
            "access_token" : userAccount.access_token!,
            "uid" : userAccount.uid!
        ]
        
        request(PHNetworktoolsType.GET, urlString: urlString, parameters: params, success: success, failure: failure)

        
    }
    
    //请求微博主页数据
    func getHomeData(success:(response: AnyObject?)->(),failure:(error: NSError)->()) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params = ["access_token" : PHUserAccountView.sharedTools.accessToken!]

        
        request(PHNetworktoolsType.GET, urlString: urlString, parameters: params, success: success, failure: failure)
        
        
    }
    
    
}















